import report from './lib/report';
import getFirstScreenTime from './lib/firstRender';
class Monitor {
  constructor() {
    this.config = null;
    this.performance = {};
    this.rewriteFetch();
    this.detectError();
    this.ready_time = -1;
    getFirstScreenTime().then((res) => {
      this.ready_time = res;
    });
  }
  /**
   * 初始化配置信息
   * @param {*} config
   */
  init(config) {
    this.config = config;
    this.reportDevice();
  }
  /**
   * 初始化登录信息
   * @param {*} userId
   */
  login(userId) {}
  getStartTime() {}

  uploadPerfamance() {
    // 判断页面是否变化
    if (this.config.currentPage == location.href) return;
    this.config.currentPage = location.href;
    // 判断是否支持performance
    if (!window.performance) return;
    const timing = performance.timing;
    this.performance = {
      dns_time: timing.domainLookupEnd - timing.domainLookupStart,
      tcp_time: timing.connectEnd - timing.connectStart,
      white_time: timing.responseStart - timing.navigationStart,
      dom_time: timing.domContentLoadedEventEnd - timing.domContentLoadedEventStart,
      load_time: timing.loadEventEnd - timing.loadEventStart,
      ready_time: timing.fetchStart - timing.navigationStart,
      unload_time: timing.unloadEventEnd - timing.unloadEventStart,
      request_time: timing.responseEnd - timing.requestStart,
      analysisDom_time: timing.domComplete - timing.domInteractive,
      firstRender_time: this.ready_time,
    };

    report({
      report_type: 'page',
      app_id: this.config.appId,
      ...this.performance,
    });
  }

  /**
   * 重写fetch
   */
  rewriteFetch() {
    const originFetch = window.fetch;
    const _this = this;
    window.fetch = function (...args) {
      const startTime = Date.now();
      return new Promise((resolve, reject) => {
        originFetch.apply(null, args).then((res) => {
          resolve(res);
          // 开始上报数据
          const url = args[0];
          if (url && url.indexOf('/monitor/web/report') <= 0) {
            report({
              report_type: 'ajax',
              url: url,
              data: args,
              duration: Date.now() - startTime,
              app_id: _this.config.appId,
            });
          }
          // 页面统计
          _this.uploadPerfamance();
        });
      });
    };
  }

  /**
   * 监听系统错误
   */
  detectError() {
    const _this = this;
    window.onerror = function (e) {
      console.log('【SDK】监听到一个错误', e);
      report({
        report_type: 'error',
        content: e,
        app_id: _this.config.appId,
      });
      return true;
    };
  }

  /**
   * 上报设备信息
   */
  reportDevice() {
    report({
      report_type: 'device',
      app_id: this.config.appId,
    });
  }
}
let monitor = new Monitor();
export default monitor;
